//
//  WBlistTableViewController.m
//  sinawb
//
//  Created by ibokan on 14-11-12.
//  Copyright (c) 2014年 ibokan. All rights reserved.
//

#import "WBlistTableViewController.h"
#import "AFNetworking.h"

@interface WBlistTableViewController ()
{
    UIView *background;
}
@property (strong,nonatomic)NSArray *wbarray;
@property (assign, nonatomic) BOOL isBig;
@property (strong, nonatomic) UIImage *img;

@end

@implementation WBlistTableViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.isBig = NO;
    
//    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imagePressed)];
//    self.imgView.userInteractionEnabled = YES;
//    [self.imgView addGestureRecognizer:tapGestureRecognizer];
   
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didFinishedPublishWB) name:@"PUBLISH" object:nil];
    
//    self.tableView.delegate = self;
//    self.tableView.dataSource = self;
//    self.wbarray = [NSMutableArray arrayWithCapacity:100];
    
//    https://api.weibo.com/2/statuses/user_timeline.json
//    @"https://api.weibo.com/2/statuses/public_timeline.json"
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *token = (NSString *)[[NSUserDefaults standardUserDefaults]objectForKey:@"accessToken"];
	NSDictionary *dic = @{@"access_token": token};
    
    //获取微博内容
    [manager GET:@"https://api.weibo.com/2/statuses/user_timeline.json" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic1 = responseObject;
        self.wbarray = dic1[@"statuses"];
//        NSLog(@"%@",self.wbarray);
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"-------");
    }];
    
    
    
    
    
    
    
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


-(void)didFinishedPublishWB{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *token = (NSString *)[[NSUserDefaults standardUserDefaults]objectForKey:@"accessToken"];
	NSDictionary *dic = @{@"access_token": token};
    
    [manager GET:@"https://api.weibo.com/2/statuses/user_timeline.json" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic1 = responseObject;
        self.wbarray = dic1[@"statuses"];
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"-------");
    }];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    // Return the number of rows in the section.
//    NSLog(@"%d-------",self.wbarray.count);
    
    return self.wbarray.count;
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSDictionary *wDic = self.wbarray[indexPath.row];
    if (wDic[@"original_pic"] == nil) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        cell.userInteractionEnabled = NO;
        UITextView *label = (UITextView *)[cell.contentView viewWithTag:1];
        
        //微博内容
        label.text = wDic[@"text"];
        NSDictionary *userdic = wDic[@"user"];
        //微博作者个人信息
        UIImageView *imageView2 = (UIImageView *)[cell.contentView viewWithTag:2];
        NSURL *url2 = [NSURL URLWithString:userdic[@"profile_image_url"]];
        NSURLRequest *request = [NSURLRequest requestWithURL:url2];
        NSData *data2 = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        imageView2.image = [UIImage imageWithData:data2];
        
        UILabel *label3 = (UILabel *)[cell.contentView viewWithTag:3];
        label3.text = userdic[@"screen_name"];
        NSLog(@"%@",label3.text);
        UILabel *label4 = (UILabel *)[cell.contentView viewWithTag:4];
        label4.text = userdic[@"location"];
        return cell;
    }else{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"picCell" forIndexPath:indexPath];
#pragma mark 为了让图片手势响应，此处将其释放
//        cell.userInteractionEnabled = NO;
        UITextView *label = (UITextView *)[cell.contentView viewWithTag:1];
        label.text = wDic[@"text"];//微博文本内容
        NSDictionary *userdic = wDic[@"user"]; //微博作者个人信息
        
        UIImageView *imageView2 = (UIImageView *)[cell.contentView viewWithTag:2];//作者头像
        NSURL *url2 = [NSURL URLWithString:userdic[@"profile_image_url"]];
        NSURLRequest *request = [NSURLRequest requestWithURL:url2];
        NSData *data2 = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        imageView2.image = [UIImage imageWithData:data2];
        
        UILabel *label3 = (UILabel *)[cell.contentView viewWithTag:3];//作者昵称
        label3.text = userdic[@"screen_name"];
        
        UILabel *label4 = (UILabel *)[cell.contentView viewWithTag:4];//作者地址
        label4.text = userdic[@"location"];
        
        UIImageView *imageView5 = (UIImageView *)[cell.contentView viewWithTag:5];//微博图片

        //设置图片可响应
        imageView5.userInteractionEnabled = YES;
        //为图片添加手势
        UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imagePressed)];
        [imageView5 addGestureRecognizer:tapGestureRecognizer];
        
        NSURL *url5 = [NSURL URLWithString:wDic[@"original_pic"]];
        NSURLRequest *request5 = [NSURLRequest requestWithURL:url5];
        NSData *data5 = [NSURLConnection sendSynchronousRequest:request5 returningResponse:nil error:nil];
        imageView5.image = [UIImage imageWithData:data5];
        self.img = imageView5.image;
        
        return cell;
    }
}



-(void)imagePressed{
    
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 548)];
    background = bgView;
    [bgView setBackgroundColor:[UIColor colorWithRed:0.3 green:0.3 blue:0.3 alpha:0.5]];
     UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imagePressed)];
    bgView.userInteractionEnabled = YES;
    if (self.isBig) {
        self.isBig = NO;
        [background removeFromSuperview];
    }else{
        self.isBig = YES;
        
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 548)];
        [imageView setImage:self.img];
        imageView.userInteractionEnabled = YES;
        [bgView addGestureRecognizer:tapGestureRecognizer];
//        imageView.center = bgView.center;
        [bgView addSubview:imageView];
        
        
        
        //动画效果
        CGContextRef context = UIGraphicsGetCurrentContext();
        [UIView beginAnimations:nil context:context];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [UIView setAnimationDuration:2.6];//动画时间长度，单位秒，浮点数
        [self.view exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
        [UIView setAnimationDelegate:bgView];
        // 动画完毕后调用animationFinished
//        [UIView setAnimationDidStopSelector:@selector(animationEnded:)];
        [UIView commitAnimations];
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *wDic = self.wbarray[indexPath.row];
    if (wDic[@"original_pic"] == nil) {
    return 120;
    }else return 260;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
